package com.lidx.back.statistics.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lidx.back.statistics.dao.IMaterialCategoryDao;
import com.lidx.back.statistics.entity.MaterialCategory;
@Repository
public class MaterialCategoryDaoImpl implements IMaterialCategoryDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public void insertMaterialCategory(MaterialCategory category) throws Exception {
		// TODO Auto-generated method stub
		try{
			Session session = sessionFactory.getCurrentSession();
			session.save(category);
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("数据库插入数据出错");
		}
		
	}

	public void deleteMaterialCategory(MaterialCategory category) {
		Session session = this.getSession();
		Query query = session.createQuery("delete from MaterialCategory where categoryId=:categoryId")
				.setInteger("categoryId", category.getCategoryId());
		query.executeUpdate();
	}

	public List<MaterialCategory> findCategories(String sex) {
		StringBuffer sb = new StringBuffer("from MaterialCategory where 1=1");
		if(StringUtils.isNotBlank(sex)){
			sb.append(" and gender = '").append(sex).append("'");
		}
		Query query = this.getSession().createQuery(sb.toString());
		query.setCacheable(true);
		query.setCacheRegion("materialCategory");
		List list = query.list();
		return list;
	}

}
